<template>
  <div>
    <div class="h12" />
    <el-card>
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
        <el-tab-pane label="设备控制" name="first">
          <div class="action-container">
            <div v-for="(item,index) in rtuActionDisplays" :key="index" class="action-board">
              <b>{{ item.name }}：</b>
              <el-button-group v-if="item.action_type == 'select'">
                <el-button
                  v-for="(citem,cindex) in item.action_arr"
                  :key="cindex"
                  size="small"
                  :type="getButtonType(item,cindex)"
                  @click="citem.params === 'fkq'?openFkqModal(item):sendCommand(citem, item)"
                >{{ citem.name }}</el-button>
              </el-button-group>
              <span v-if="['raw','input'].includes(item.action_type)" style="margin-left:auto;width:100%;">
                <el-slider
                  v-model="item.default_val"
                  show-input
                  @change="changeSlider(item)"
                />
              </span>
              <el-input v-if="item.action_type == 'inputRaw'" v-model="item.default_val" type="number" :placeholder="item.name" clearable @blur="changeSlider(item)">
                <template slot="append">{{ item.unit }}</template>
              </el-input>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="操作履历" name="second">
          <template slot="label">
            <div class="flex align-items-center">
              <span>操作履历</span>
              <div v-if="activeName==='second'">
                <i class="el-icon-refresh ml12 mr12 font18" @click.stop="refresh" />
                <!-- <el-switch v-model="autoRefresh" inactive-text="不自动刷新" active-text="自动刷新" :inactive-value="0" :active-value="1"></el-switch> -->
              </div>
            </div>
          </template>
          <el-empty v-if="actionDays.length === 0" description="暂无记录" />
          <el-tabs v-else :tab-position="tabPosition" @tab-click="handleClick">
            <el-tab-pane v-for="(item,index) in actionDays" :key="index" v-loading="loading" :label="item">
              <div class="h12" />
              <el-radio-group v-model="reverse" style="margin-left:40px;">
                <el-radio :label="true">倒序</el-radio>
                <el-radio :label="false">正序</el-radio>
              </el-radio-group>
              <div class="h12" />
              <div style="max-height:500px;overflow-y:scroll;padding:10px 0 24px 0;">
                <el-timeline :reverse="reverse">
                  <el-timeline-item
                    v-for="(citem, cindex) in actions"
                    :key="cindex"
                    placement="top"
                    :timestamp="citem.time"
                  >
                    <div>
                      <div class="h12" />
                      <div><span class="mr12">{{ citem.name }}</span> <b :class="getClass(citem.action)">{{ citem.action }}</b></div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane v-if="user.superable && currentDevice.settings && currentDevice.settings.bddx" label="北斗导向" name="third">
          <el-tabs v-model="activeCName">
            <el-tab-pane label="实时位置" name="first">
              <mqtt-container ref="mqttContainer" :topic="topic" />
              <el-descriptions :column="4" label-class-name="labelClass" content-class-name="contentClass" border>
                <el-descriptions-item v-for="(item,index) in gisAttrs" :key="index" :label="item.name">
                  {{ rtk[item.namekey] && rtk[item.namekey] + (item.unit || '') || '--' }}
                </el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>
            <el-tab-pane label="配置信息" name="second">
              <el-collapse v-model="activeNames">
                <el-collapse-item title="navi" name="1">
                  <template slot="title">
                    <div class="flex" style="width:100%;align-items:center;">
                      <b>navi设置</b>
                      <el-button class="mlauto" type="success" style="height:32px;" @click.stop="getNaviSettings">刷新</el-button>
                      <el-button class="mlauto mr12" type="primary" style="height:32px;" @click.stop="setNaviSettings">保存</el-button></div>
                  </template>
                  <el-descriptions label-class-name="labelClass" content-class-name="contentClass" border>
                    <el-descriptions-item v-for="(item,index) in naviAttrs" :key="index" :label="item.name">
                      <el-input v-if="['text','number','digit'].includes(item.type)" v-model="naviData[item.namekey]" :placeholder="item.name" clearable :type="item.type">
                        <template v-if="item.unit" slot="append">{{ item.unit }}</template>
                      </el-input>
                      <el-select v-if="item.type === 'select'" v-model="naviData[item.namekey]">
                        <el-option v-for="(citem,cindex) in item.items" :key="cindex" :label="citem.name" :value="citem.value" />
                      </el-select>
                      <el-switch v-if="item.type==='switch'" v-model="naviData[item.namekey]" />
                    </el-descriptions-item>
                  </el-descriptions>
                </el-collapse-item>
                <el-collapse-item title="rtcm" name="2">
                  <template slot="title">
                    <div class="flex" style="width:100%;align-items:center;">
                      <b>rtcm设置</b>
                      <el-button class="mlauto" type="success" style="height:32px;" @click.stop="getRtcmSettings">刷新</el-button>
                      <el-button class="mlauto mr12" type="primary" style="height:32px;" @click.stop="setRtcmSettings">保存</el-button></div>
                  </template>
                  <el-descriptions label-class-name="labelClass" content-class-name="contentClass" border>
                    <el-descriptions-item v-for="(item,index) in rtcmAttrs" :key="index" :label="item.name">
                      <el-input v-if="['text','number','digit'].includes(item.type)" v-model="rtcmData[item.namekey]" :placeholder="item.name" clearable :type="item.type">
                        <template v-if="item.unit" slot="append">{{ item.unit }}</template>
                      </el-input>
                      <el-select v-if="item.type === 'select'" v-model="rtcmData[item.namekey]">
                        <el-option v-for="(citem,cindex) in item.items" :key="cindex" :label="citem.name" :value="citem.value" />
                      </el-select>
                      <el-switch v-if="item.type==='switch'" v-model="rtcmData[item.namekey]" />
                    </el-descriptions-item>
                  </el-descriptions>
                </el-collapse-item>
                <el-collapse-item title="ntrip" name="3">
                  <template slot="title">
                    <div class="flex" style="width:100%;align-items:center;">
                      <b>ntrip设置</b>
                      <el-button class="mlauto" type="success" style="height:32px;" @click.stop="getNtripSettings">刷新</el-button>
                      <el-button class="mlauto mr12" type="primary" style="height:32px;" @click.stop="setNtripSettings">保存</el-button></div>
                  </template>
                  <el-descriptions label-class-name="labelClass" content-class-name="contentClass" border>
                    <el-descriptions-item v-for="(item,index) in ntripAttrs" :key="index" :label="item.name">
                      <el-input v-if="['text','number','digit'].includes(item.type)" v-model="ntripData[item.namekey]" :placeholder="item.name" clearable :type="item.type">
                        <template v-if="item.unit" slot="append">{{ item.unit }}</template>
                      </el-input>
                      <el-select v-if="item.type === 'select'" v-model="ntripData[item.namekey]">
                        <el-option v-for="(citem,cindex) in item.items" :key="cindex" :label="citem.name" :value="citem.value" />
                      </el-select>
                      <el-switch v-if="item.type==='switch'" v-model="ntripData[item.namekey]" />
                    </el-descriptions-item>
                  </el-descriptions>
                </el-collapse-item>
              </el-collapse>
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane label="上报统计" name="fourth">
          <div class="tip d-flex" style="padding:12px;">
            <el-date-picker
              v-model="searchForm.timetran"
              class="mr12"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            />
            <el-select
              v-model="searchForm.namekey"
              class="mr12"
              clearable
              filterable
              placeholder="属性"
            >
              <el-option
                v-for="(item,index) in rtuPortDisplays"
                :key="index"
                :label="item.name"
                :value="item.namekey"
              />
            </el-select>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="default" @click="reset">重置</el-button>
            <b v-if="censusCount !== ''" class="font16 color-danger mlauto" style="line-height:32px;">上报总次数：{{ censusCount }}</b>
          </div>
          <div class="h12" />
          <el-empty v-if="censusData.length === 0" description="暂无任何记录" />
          <el-table
            v-else
            border
            :data="censusData"
            height="400"
            style="width: 100%"
          >
            <el-table-column
              align="center"
              prop="time_start"
              label="起始时间"
              width="240"
            />
            <el-table-column
              align="center"
              prop="time_end"
              label="结束时间"
              width="240"
            />
            <el-table-column
              align="center"
              prop="val"
              label="上报次数"
              width="240"
            />
          </el-table>
        </el-tab-pane>
        <el-tab-pane v-if="isSprinkler" label="分区设置" name="fifth">
          <partition :partition-serialno="partitionSerialno" />
        </el-tab-pane>
        <el-tab-pane v-if="isSprinkler" label="灌溉计划" name="sixth">
          <pgPlan ref="pgPlan" :show-header="false" />
        </el-tab-pane>
        <el-tab-pane v-if="isSprinkler" label="处方图" name="seventh">
          <pgPlan ref="pgPlan" :show-header="false" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      v-el-drag-dialog
      title="喷头控制"
      :append-to-body="true"
      destroy-on-close
      :visible.sync="dialogVisible"
      width="600px"
    >
      <div class="tags">
        <el-tag
          v-for="(item,index) in formData.valves"
          :key="index"
          closable
          type="primary"
          style="margin:8px 8px 8px 0;"
          @close="closeTag(index)"
        >
          {{ item.name }}
        </el-tag>
      </div>
      <div class="h20" />
      <el-form ref="form" :rules="rules" :model="formData" label-suffix="：" label-width="100px">
        <el-form-item label="启闭设定" prop="cycle">
          <el-radio-group v-model="actionType" @change="changeActionType">
            <el-radio :label="1">打开</el-radio>
            <el-radio :label="0">关闭</el-radio>
            <el-radio :label="2">占空比</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="12"><el-form-item label="脉冲周期" prop="cycle">
            <el-input v-model="formData.cycle" placeholder="脉冲周期">
              <template slot="append">秒</template>
            </el-input>
          </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="占空比" prop="PWM">
            <el-input v-model="formData.PWM" placeholder="占空比">
              <template slot="append">%</template>
            </el-input>
          </el-form-item></el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" icon="el-icon-check" @click="pwmValve('form')">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { sendPWM, sendCommand } from '@/api/device'
import { getActions, getActionDays } from '@/api/statistics'
import { getNaviSettings, setNaviSettings, getRtcmSettings, setRtcmSettings, getNtripSettings, setNtripSettings, systemRestart } from '@/api/settings'
import { naviAttrs, rtcmAttrs, ntripAttrs, gisAttrs, dclassCodeMap } from '@/utils/constant'
import { sum } from '@/utils'
import { formatSprinklerRate } from '@/utils/device'
import MqttContainer from '@/components/MqttContainerExtra/index'
import Partition from '@/views/dashboard/components/partition'
import PgPlan from '@/views/pgPlan/index'
import { getAll } from '@/api/census'
export default {
  components: {
    MqttContainer,
    Partition,
    PgPlan
  },
  data() {
    return {
      topic: '',
      activeCName: 'first',
      naviAttrs,
      naviData: {},
      rtcmAttrs,
      rtcmData: {},
      ntripAttrs,
      ntripData: {},
      gisAttrs,
      activeNames: ['1'],
      dialogVisible: false,
      childSelected: [],
      formData: {
        cycle: 60,
        PWM: 60,
        type: 'valves',
        valves: []
      },
      actionType: 2,
      rules: {
        cycle: [
          { required: true, message: '请输入脉冲周期', trigger: 'blur' }
        ],
        PWM: [
          { required: true, message: '请输入占空比', trigger: 'blur' }
        ]
      },
      activeName: 'first',
      actionDays: [],
      searchDate: '',
      current: 0,
      page: 1,
      pages: 1,
      reverse: true,
      actions: [],
      loading: false,
      tabPosition: 'left',
      sliderValue: 0,
      rtuActionDisplays: [],
      states: {},
      autoRefresh: 0,
      intelval: null,
      searchForm: {
        timetran: '',
        namekey: ''
      },
      censusData: [],
      censusCount: ''
    }
  },
  computed: {
    ...mapGetters(['currentDevice', 'currentDeviceShow', 'rtk', 'user']),
    partitionSerialno() {
      return this.currentDevice.serialno
    },
    isSprinkler() {
      const res = this.currentDevice.product_type === dclassCodeMap.pg
      console.log(res)
      return res
    },
    rtuPortDisplays() {
      return this.currentDevice.rtuPortDisplays || []
    },
    actionListener() {
      const serialno = this.currentDevice.serialno
      const activeName = this.activeName
      return { serialno, activeName }
    }
  },
  watch: {
    // autoRefresh:{
    //   handler(newVal){
    //     if(newVal === 1){
    //       if(this.intelval){
    //         clearInterval(this.intelval)
    //       }
    //       this.intelval = setInterval(() => {
    //         this.getActions()
    //       },5000)
    //     } else {
    //       console.log(this.intelval,'clear')
    //       clearInterval(this.interval)
    //     }
    //   },
    //   immediate:true
    // },
    currentDevice: {
      handler(newVal, oldVal) {
        this.rtuActionDisplays = newVal.rtuActionDisplays
        this.rtuActionDisplays.map(val => {
          val.default_val = +val.default_val
          if (typeof (val.action_arr) === 'string') {
            val.action_arr = JSON.parse(val.action_arr)
          }
        })
        this.states = newVal.states
        if (newVal.states && newVal.states.REG_HMI_PWM) {
          this.sliderValue = Number(newVal.states.REG_HMI_PWM)
        }

        if (newVal.settings && newVal.settings.bddx) {
          this.topic = `G/${newVal.settings.bddx.url.split(':')[0]}/#`
          this.getNaviSettings()
          this.getRtcmSettings()
          this.getNtripSettings()
        }
      },
      deep: true,
      immediate: true
    },
    actionListener: {
      handler(newVal) {
        if (newVal.serialno && newVal.activeName === 'second') {
          this.getActionDays()
        }
      },
      immediate: true
    },
    searchDate: {
      handler(newVal) {
        if (newVal) {
          this.actions = []
          this.getActions()
        }
      },
      immediate: true
    },
    currentDeviceShow: {
      handler(newVal) {
        if (this.currentDevice.settings && this.currentDevice.settings.bddx) {
          if (!newVal) {
            this.resetActive()
            this.$refs.mqttContainer.destroyConnection()
          } else {
            this.$nextTick(() => {
              this.$refs.mqttContainer.createConnection()
            })
          }
        }
      },
      immediate: true
    },
    activeName: {
      handler(newVal) {
        if (newVal === 'sixth') {
          this.$refs.pgPlan.changeDevice(this.currentDevice.serialno)
        }
      },
      immediate: true
    }
  },
  methods: {
    handleTabClick(e) {
      if (e.name === 'sixth') {
        this.$refs.pgPlan.changeDevice(this.currentDevice.serialno) 
      }
    },
    reset() {
      this.searchForm = {
        serialno: '',
        timetran: '',
        namekey: ''
      }
      this.censusCount = ''
      this.censusData = []
    },
    async search() {
      if (!this.searchForm.timetran) {
        this.$message.error('请选择时间区间')
        return
      }
      if (!this.searchForm.namekey) {
        this.$message.error('请选择属性名称')
        return
      }
      this.searchForm.serialno = this.currentDevice.serialno
      console.log(this.searchForm)
      const { data } = await getAll(this.searchForm)
      this.censusData = data
      this.censusCount = sum(data.map(val => val.val))
    },
    refresh() {
      this.actions = []
      this.getActions()
    },
    getSubmitData(currentAttrs, currentData) {
      const data = {}
      currentAttrs.forEach(item => {
        data[item.namekey] = currentData[item.namekey]
      })
      return data
    },
    async getNaviSettings() {
      const { data } = await getNaviSettings(this.currentDevice.serialno)
      this.naviData = data
    },
    async setNaviSettings() {
      const submitData = this.getSubmitData(this.naviAttrs, this.naviData)
      const { data } = await setNaviSettings(this.currentDevice.serialno, submitData)
      this.systemRestart()
      console.log(data)
    },
    async getRtcmSettings() {
      const { data } = await getRtcmSettings(this.currentDevice.serialno)
      this.rtcmData = data
    },
    async setRtcmSettings() {
      const submitData = this.getSubmitData(this.rtcmAttrs, this.rtcmData)
      const { data } = await setRtcmSettings(this.currentDevice.serialno, submitData)
      this.systemRestart()
      console.log(data)
    },
    async getNtripSettings() {
      const { data } = await getNtripSettings(this.currentDevice.serialno)
      this.ntripData = data
    },
    async setNtripSettings() {
      const submitData = this.getSubmitData(this.ntripAttrs, this.ntripData)
      const { data } = await setNtripSettings(this.currentDevice.serialno, submitData)
      this.systemRestart()
      console.log(data)
    },
    async systemRestart() {
      const { msg } = await systemRestart(this.currentDevice.serialno)
      this.$message.success(msg)
    },
    pwmValve() {
      this.$confirm('确定要进行此操作吗？', '操作确认', { type: 'warning' }).then(() => {
        sendPWM(this.formData).then(res => {
          this.$message({ message: res.msg, type: 'success', showClose: true })
        })
      })
    },
    closeTag(index) {
      this.formData.valves.splice(index, 1)
    },
    changeActionType(val) {
      const map = {
        1: 100,
        0: 0,
        2: 60
      }
      this.formData.cycle = 60
      this.formData.PWM = map[val]
    },
    openFkqModal(item) {
      const rtuActionDisplays = this.currentDevice.rtuActionDisplays.filter((val) => {
        return val.action_arr[0].namekey.indexOf('SetPulse') > -1
      })
      const valves = []
      rtuActionDisplays.forEach((val) => {
        const port = val.action_arr[0].namekey.replace('SetPulse_', '')
        valves.push({
          rtu_serialno: this.currentDevice.serialno,
          port: +port,
          name: val.name
        })
      })
      this.formData.valves = valves
      this.dialogVisible = true
    },
    resetActive() {
      this.activeName = 'first'
      this.searchDate = ''
      this.actionDays = []
    },
    async getActionDays() {
      const { data } = await getActionDays(this.currentDevice.serialno)
      this.actionDays = data
      this.searchDate = this.actionDays[this.current]
    },
    async getActions() {
      this.loading = true
      const { data } = await getActions({
        serialno: this.currentDevice.serialno,
        time: this.searchDate,
        page: this.page,
        pageSize: 100
      })
      this.loading = false
      this.convertData(data)
    },
    handleClick(e) {
      this.searchDate = e.label
    },
    getClass(action) {
      if (action.indexOf('开') > -1 || action.indexOf('启动') > -1) {
        return 'color-success'
      }
      if (action.indexOf('关') > -1 || action.indexOf('停止') > -1) {
        return 'color-danger'
      }
      return ''
    },
    convertData(data) {
      this.actions = this.actions.concat(data.data)
      this.page = data.current_page
      this.pages = data.last_page
    },
    sendCommand(item, pitem) {
      this.$confirm('确定要进行此操作吗？', '操作确认', { type: 'warning' }).then(() => {
        if (Array.isArray(item.namekey)) {
          item.namekey.forEach((val) => {
            const data = {
              namekey: val,
              params: item.params
            }
            this._sendCommand(data, pitem)
          })
        } else {
          const data = {
            namekey: item.namekey,
            value: item.params
          }
          if (item.group) {
            data.group = item.group
          }
          this._sendCommand(data, pitem)
        }
      })
    },
    async _sendCommand(data, item) {
      const serialno = item.rtu_serialno || this.currentDevice.serialno
      const res = await sendCommand(data, serialno)
      if (res.errorCode === 0) {
        this.$message({ message: '操作成功', type: 'success', showClose: true })
      }
    },
    changeSlider(item) {
      const kunit = item.kunit || 1
      let sliderValue = Number(item.default_val)
      this.$confirm(`确定要将${item.name}设置为 ${sliderValue}${item.unit || ''} 吗？`, '操作确认', { type: 'info' }).then(() => {
        if (item.mode && item.mode === 'hex') {
          sliderValue = formatSprinklerRate(sliderValue, item.prefix)
        }
        if (item.offset) {
          sliderValue = +sliderValue + +item.offset
        }
        const data = {
          namekey: item.action_arr[0].namekey,
          value: sliderValue * kunit
        }
        this._sendCommand(data, item)
      })
    },
    getButtonType(item, cindex) {
      if (item.show_state && item.mode !== 'raw') {
        const state_arr = JSON.parse(item.state_arr)
        let state = {}
        if (typeof (state_arr.namekey) === 'string') {
          state = +this.currentDevice.states[state_arr.namekey]
        } else {
          state = +this.currentDevice.states[(state_arr.namekey)[cindex]]
        }

        return state_arr.state[cindex] && state === +(state_arr.state[cindex]) ? 'primary' : 'default'
      }
      return 'default'
    }
  }
}
</script>

<style lang="scss" scoped>
.action-board{
display:flex;
align-items: center;
float:left;width:33%;
margin:6px 0.15%;
  b{
    display:inline-block;
    width:100px;
    text-align:right;
  }
}
</style>
